package com.ifnk.portaljava.dapWeb.socket;

import com.ifnk.portaljava.dapWeb.dapweb.Command;
import com.ifnk.portaljava.dapWeb.dataPacket.TypeDefine;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpSession;

public class TimerTask {
	private static Log loger = LogFactory.getLog(TimerTask.class);
	
	private static final long TIMEOUT = 60;

	class HeartSend extends java.util.TimerTask {
		private String clientId;
		private SocketProperty sp;
		@SuppressWarnings("unused")
		private ClientProperty cp;
		// 心跳包
		@SuppressWarnings("unused")
		private byte[] beatPacket;
		@SuppressWarnings("unused")
		private int len;

		public HeartSend(ClientProperty cp, SocketProperty sp) {
			this.clientId = cp.getRequestDateFromProxyId();
			loger.debug("create heartsend id: "+clientId);
			this.sp = sp;
			this.cp = cp;
			this.init();
		}

		public void init() {
			Command command = new Command();
			loger.debug("init heartsend id: "+this.clientId);
			byte[] beatData = new byte[60];
			command.setSessionId(this.clientId);
			int cmd = TypeDefine.WWW_KEEPALIVE;
			try {
				len = command.EncodeHeartBeat(beatData, beatData.length, cmd);
				this.beatPacket = beatData;
			} catch (Exception e) {
				e.printStackTrace();
				loger.error("WebServer Exception " + e.toString());
			}
		}

		public void run() {
			//try {
				if (sp.out != null) {
					// no heart beat send now
					/*
					sp.out.write(beatPacket, 0, len);
					sp.out.flush();
					*/
					
//					Date now = new Date();
//					DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);

					//loger.debug(formatter.format(now)+" send uuid:"+this.clientId+" cliendId:"+cp.getClientId());
//					loger.info("WebServer Send KeepAlive Packet Success! send uuid:"+this.clientId+" cliendId:"+cp.getClientId());
				} else {
					sp.setIsNetConnected(false);
					sp.flag = false;
					loger.error("WebServer Send KeepAlive Packet Failed");
				}
			//} 
			/*
			catch (IOException e) {
				sp.setIsNetConnected(false);
				sp.flag = false;
				loger.error("WebServer Exception Dapweb Send KeepAlive Packet Failed "
								+ e.toString());
			}
			*/
		}

		public void destroy() {
			this.cancel();
		}
	}

	class SessionOver extends java.util.TimerTask {
		private String clientId;
		public HttpSession session;
		private SocketProperty sp;
		private ClientProperty cp;

		public SessionOver(String clientId, HttpSession session,
				SocketProperty sp,
				ClientProperty cp
				) {
			this.clientId = clientId;
			this.session = session;
			this.sp = sp;
			this.cp = cp;
		}

		public void run() {
			try {
				Long time = (Long) session.getAttribute(clientId);
				Long dur = System.currentTimeMillis() / 1000 - time;
				if (dur > TIMEOUT) {
					sp.setFlag(false);
					cp.setTimeout(true);
					// remove client when timeout, or memory leak
					// sleep sometime for put a new client with same clientId concurrently
					//Thread.sleep(2000);
					//CallTraceServlet.removeStoppedClient(clientId);
					loger.info("WebServer Html Page Closed"+dur);
					
				}
			} catch (Exception e) {
				sp.setFlag(false);
				cp.setTimeout(true);
				loger.error("WebServer Exception HttpSession invalidated");
			}
		}

		public void destroy() {
			this.cancel();
			sp.setFlag(false);
			cp.setTimeout(true);
		}
	}

	class HeartBeat extends java.util.TimerTask {
		private ClientProperty cp;
		private SocketProperty sp;

		public HeartBeat(ClientProperty cp, SocketProperty sp) {
			this.cp = cp;
			this.sp = sp;
		}

		public void run() {

			if (cp.getKeepLiveTime() == 0) {
				cp.setKeepLiveTime(System.currentTimeMillis() / 1000);
			}
			
			long time = System.currentTimeMillis() / 1000
					- cp.getKeepLiveTime();
		
			// now if no data for 12 minutes then clear the connect
			if (time > TIMEOUT && sp.isNetConnected) {
				loger.info("WebServer not receive heartbeat packet in time "+time+" , "+cp.getKeepLiveTime()+" , "+System.currentTimeMillis() / 1000);
				sp.setFlag(false);
				//loger.error("WebServer not receive heartbeat packet in time "+time+" , "+cp.getKeepLiveTime()+" , "+System.currentTimeMillis() / 1000);
			}
		}

		public void destroy() {
			this.cancel();
		}
	}
}
